const Service = require('egg').Service;
const bcrypt = require('bcryptjs');

class UserService extends Service {
  // 注册接口
  async register() {
    const { ctx } = this;
    const { phone_number, password, avatar, gender, age, birthplace, residence, occupation, medical_history, role } = ctx.request.body;
    const hashedPassword = bcrypt.hashSync(password, 10);
    const result = await ctx.app.mysql.insert('users', {
      phone_number,
      password: hashedPassword,
      avatar,
      gender,
      age,
      birthplace,
      residence,
      occupation,
      medical_history,
      role
    
    });
    return result
  }
  async create() {
    const { ctx } = this;
    const { phone_number, password, avatar, gender, age, birthplace, residence, occupation, medical_history, role ,  major,
      name} = ctx.request.body;
    const hashedPassword = bcrypt.hashSync(password, 10);
    const result = await ctx.app.mysql.insert('users', {
      phone_number,
      password: hashedPassword,
      avatar,
      gender,
      age,
      birthplace,
      residence,
      occupation,
      medical_history,
      role,
      major,
      name
    
    });
    return result
  }

  // 登录接口
  async login() {
    const { ctx } = this;
    const { phone_number, password } = ctx.request.body;
    const result = await ctx.app.mysql.get('users', { phone_number });
    return result
  }

  // 获取所有用户
  async list() {
    const { ctx } = this;
    const result = await ctx.app.mysql.select('users');
    return result
  }

  // 获取单个用户
  async read() {
    const { ctx } = this;
    const id = ctx.params.id;
    const result = await ctx.app.mysql.get('users', { id });
    return result
  }

  async listDoctors() {
    const { ctx } = this;
    const result = await ctx.app.mysql.select('users', {
      where: { role: 'doctor' } // 确保角色为“医生”
    });
    return result
  }
  

  // 更新用户信息
  async update() {
    const { ctx } = this;
    const id = ctx.params.id;
    const { avatar, gender, age, birthplace, residence, occupation, medical_history, role } = ctx.request.body;
    const result = await ctx.app.mysql.update('users', {
      avatar,
      gender,
      age,
      birthplace,
      residence,
      occupation,
      medical_history,
      role
    }, {
      where: { id }
    });
    return result
  }

  // 删除用户
  async delete() {
    const { ctx } = this;
    const id = ctx.params.id;
    const result =  await ctx.app.mysql.delete('users', { id });
    return result
  }
}

module.exports = UserService;
